package Synchronized;

public class TestDeadLock {
    public static void main(String[] args) throws InterruptedException {
        Object o = new Object();
        MyThread myThread1 = new MyThread(o);
        MyThread2 myThread2 = new MyThread2(o);
        myThread1.start();
        myThread2.start();
        //主线程通知完俩个线程再休眠
        Thread.sleep(3000);
        synchronized (o){
            System.out.println(Thread.currentThread().getName()+"进入到同步代码块");
            try {
                o.wait();//主线程拿到锁然后主动释放,进行等待
              //  o.notify();//拿到锁随机唤醒一个线程,另一个还在无线等待
              //  o.notifyAll();//唤醒所有等待的线程
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"退出了同步代码块");
        }
    }
}
// 复杂一个线程持有A对象的锁,需要B对象的锁,另一个持有B,需要A
//简单 一个线程持有A对象的锁,另一个线程也需要A
class MyThread extends Thread{
    Object object;
    public MyThread(Object object){
        this.object=object;
    }
    public void run(){
        synchronized (object) {
            System.out.println(Thread.currentThread().getName()+"进入到同步代码块");
           //如果Thead -0先拿到锁,然后主动释放锁给其他线程先使用
            try {
                object.wait();//主动释放当前持有的锁,并进入无限期等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"退出了同步代码块");
        }

    }
}
class MyThread2 extends Thread{
    Object object;
    public MyThread2(Object object){
        this.object=object;
    }
    public void run(){
        synchronized (object) {
            System.out.println(Thread.currentThread().getName()+"进入到同步代码块");
            object.notify();//在obj这个共享对象的等待队列,唤醒一个正在等待的线程
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"退出了同步代码块");
        }

    }
}